﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using Amap.WebApi;
using Bigway.Common.Jobs;
using Bigway.Common.Services;
using Bigway.Common.Models.DbModels;
using Bigway.Common.Services.Repositories;
using Bigway.Common.Interfaces;

namespace Bigway.Common;

public static class ServiceRegistry
{
    public static void AddCommons(this IServiceCollection services, string dbFilePath, string dbName, params Type[] entityTypes)
    {
        entityTypes = entityTypes.Prepend(typeof(SoftwareSystem)).ToArray();
        services.AddSingleton(new SqliteDbInfo(dbFilePath, dbName, entityTypes));

        var sqliteConnectionConfig = new SqliteConnectionConfig
        {
            ConnectionString = $"Data Source={dbFilePath}"
        };

        services.AddSingleton(sqliteConnectionConfig);

        services.AddScoped<SqlLogger>();

        services.AddKeyedScoped<ISqlSugarClient>(IocKeys.SqliteDbKey,
            (sp, _) => 
                sp.GetRequiredService<ISqliteAndCrmebSqlSugarClient>().SqliteSqlSugarClient
        );

        services.AddKeyedScoped<ISqlSugarClient>(IocKeys.CrmebDbKey,
            (sp, _) =>
                sp.GetRequiredService<ISqliteAndCrmebSqlSugarClient>().CrmebSqlSugarClient
        );

        services.AddScoped<ISqliteAndCrmebSqlSugarClient>(sp =>
            new SqliteAndCrmebSqlSugarClient(
                [
                    sp.GetRequiredService<SqliteConnectionConfig>(),
                    sp.GetRequiredService<CrmebConnectionConfig>()
                ])
            );

        services.AddScoped<ISoftwareSystemRepository, SoftwareSystemRepository>();
        services.AddScoped<ICrmebMerchantRepository, CrmebMerchantRepository>();

        services.AddScoped<ICrmebFrontApiClient, CrmebFrontApiClient>();
        services.AddScoped<IBigwayApiClient, BigwayApiClient>();
        services.AddScoped<IPinyinService, PinyinService>();
        services.AddAsyncInitializer<CommonInitializer>();

        services.AddSingleton<JobRegistryProvider>();
        
        services.AddAmapServices();
    }

    public static void AddAmapServices(this IServiceCollection services)
    {
        services.Configure<AmapOptions>(options => options.Key = AmapApiKey);
        services.AddOptions<AmapOptions>();

        services.AddTransient<IGeoService, GeoService>();
        services.AddTransient<IDirectionService, DirectionService>();
        services.AddTransient<IGeoDecoder, GeoDecoder>();
    }

    private const string AmapApiKey = "146e32555868844ededdbcae1e5e76e1";
}